package com.dragon.utilslibrary.tools;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import com.dragon.utilslibrary.AppConfig;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileUtils {

    private static String mPath = Environment.getExternalStorageDirectory() + File.separator + AppConfig.rootFile;
    public static final String CAMERA_IMAGE_PATH = "DCIM/Camera/";
    public static String PHOTO_PATH = mPath + CAMERA_IMAGE_PATH;
    /**
     * 手环固件文件名
     */
    public static String banName = "Musering.zip";
    /**
     * 下载后的APP文件名
     */
    public static String appName = "Musering.apk";

    /**
     * 判断指定路径文件是否存在，如果不存在直接生成一个新的文件
     *
     * @param path ： 文件指定路径
     */
    public static void isExist(String path) {
        File file = new File(path);
        // 判断文件夹是否存在,如果不存在则创建文件夹
        if (!file.exists()) {
            synchronized (FileUtils.class) {
                file.mkdirs();
            }
        }
    }

    public static boolean isFileExist(String path) {
        File file = new File(path);
        return file.exists();
    }

    /**
     * 获取本应用的数据存储路径
     *
     * @return
     */
    public static String getFolderPath() {
        String pathString = mPath;
        isExist(pathString);
        pathString += "/";
        return pathString;
    }


    /**
     * 获取保存图片本地路径
     *
     * @return
     */
    public static String getImgFolderPath() {
        String path = getFolderPath() + "image";
        isExist(path);
        path += "/";
        return path;
    }

    public static String getDownLoadPath() {
        String pathString = mPath;
        isExist(pathString);
        isExist(pathString);
        pathString = pathString + "/download";
        isExist(pathString);
        return pathString;
    }

    /**
     * 保存 JPG格式到SD卡中
     *
     * @param bitmap    源bitmap
     * @param imageName 保存图片的名称
     * @param b_quality Hint to the compressor, 0-100. 0 meaning compress for small size, 100 meaning compress for max quality. Some formats, like PNG which is lossless, will ignore the quality setting
     */
    public static void saveJPGImageToSDCard(Bitmap bitmap, String imageName, int b_quality) {
        saveImageToSDCard(bitmap, imageName, b_quality, CompressFormat.JPEG);
    }

    /**
     * 保存 PNG格式到SD卡中
     *
     * @param bitmap    源bitmap
     * @param imageName 保存图片的名称
     * @param b_quality Hint to the compressor, 0-100. 0 meaning compress for small size, 100 meaning compress for max quality. Some formats, like PNG which is lossless, will ignore the quality setting
     */
    public static void savePNGImageToSDCard(Bitmap bitmap, String imageName, int b_quality) {
        saveImageToSDCard(bitmap, imageName, b_quality, CompressFormat.PNG);
    }

    private static void saveImageToSDCard(Bitmap bitmap, String imageName, int b_quality, CompressFormat compressFormat) {
        String filePath = getImgFolderPath();
        int quality = 90;
        if (b_quality != 0) {
            quality = b_quality;
        }
        FileOutputStream fos = null;
        File file = new File(filePath, imageName);
        try {
            fos = new FileOutputStream(file);
            if (null != fos) {
                bitmap.compress(compressFormat, quality, fos);
                fos.flush();
                fos.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从程序本地文件夹中的image文件夹获取图像信息
     *
     * @return Bitmap
     */
    public static Bitmap getImageFromSDCard(String imageName) {
        String filepath = getImgFolderPath() + imageName;
        File file = new File(filepath);
        if (file.exists()) {
            Bitmap bm = BitmapFactory.decodeFile(filepath);
            return bm;
        }
        return null;
    }

    public static void saveFile(Context context, String filename, InputStream is) {
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        try {
            if (filename == null || is == null) {
                return;
            }
            bis = new BufferedInputStream(is, 1024);
            fos = new FileOutputStream(getFolderPath() + filename);
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (Exception e) {
                }
            }
        }
    }

    /**
     * 删除文件，不是删除文件夹，只需指定文件的名称，不需要整个路径
     *
     * @param fileName 图片的名称
     */
    public static void deleteImageFile(String fileName) {
        File file = new File(getImgFolderPath() + fileName);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 删除程序本地文件夹中的文件，只需指定文件名称。
     *
     * @param fileName 如对应apk名称，对应软件包名称等等
     */
    public static void deleteFile(String fileName) {
        File file = new File(getFolderPath() + fileName);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 删除整个程序本地文件夹
     *
     * @param folder
     */
    public static boolean deleteDir(File folder) {
        if (folder == null || (!folder.exists())) {
            return false;
        }
        if (null != folder.listFiles()) {
            for (File file : folder.listFiles())
                if (file.isDirectory()) {
                    deleteDir(file);
                } else {
                    file.delete();
                }
        }
        return folder.delete();
    }

    /**
     * 图片重命名
     *
     * @param oldName
     * @param newName
     */
    public static void renameForImage(String oldName, String newName) {
        String filePath = getImgFolderPath();
        File file = new File(filePath + oldName);
        file.renameTo(new File(filePath + newName));

    }

    /**
     * 按照参数条件进行bitmap的比例伸缩
     *
     * @param bmap
     * @param w
     * @param h
     * @return
     */
    public static Bitmap scaleBitmap(Bitmap bmap, int w, int h) {
        if (bmap == null) {
            return null;
        }
        int width = bmap.getWidth();
        int height = bmap.getHeight();

        float scaleWidth = ((float) w / width);
        float scaleHeight = ((float) h / width);
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBm = Bitmap.createBitmap(bmap, 0, 0, width, height, matrix, true);
        return newBm;
    }

    public static void writeTOfileAndActiveClear(String filename, String msg) {
        writeToFile("LogData/", filename, msg, true, "utf-8");
    }

    public static void writeTOfile(String filename, String msg) {
        writeToFile("MapLogData/", filename, msg, false, "utf-8");
    }

    /**
     * 向文件写入G_sensor数据
     *
     * @param filename
     * @param msg
     */
    public static void writeGsensorTOfile(String filename, String msg) {
        writeToFile("Gsensor/", filename, msg, false, "utf-8");
    }

    /**
     * 向文件写入运动数据
     *
     * @param filename
     * @param msg
     */
    public static void writeSportTOfile(String filename, String msg) {
        writeToFile("SportData/", filename, msg, false, "utf-8");
    }

    public static void writeToFileInRoot(String filename, String msg) {
        writeToFile("LogData/", filename, msg, false, "utf-8");
    }

    /**
     * 自定义文件路径
     *
     * @param middlePathName 文件夹路径
     * @param filename       文件名
     * @param msg            内容
     */
    public static void writeToFileInRoot(String middlePathName, String filename, String msg) {
        writeToFile(middlePathName, filename, msg, false, "utf-8");
    }

    /**
     *
     * @param middlePathName
     * @param filename
     * @param msg
     * @param charsetName   比如默认：utf-8
     */
    public static void writeToFileInRoot(String middlePathName, String filename, String msg, String charsetName) {
        writeToFile(middlePathName, filename, msg, false, charsetName);
    }

    /**
     * @param middlePathName
     * @param filename
     * @param msg
     * @param autoClear
     * @param charsetName   比如默认：utf-8
     */
    private static void writeToFile(String middlePathName, String filename, String msg, boolean autoClear, String charsetName) {
        if (TextUtils.isEmpty(charsetName)) {
            charsetName = "utf-8";
        }
        String path = getFolderPath();
        isExist(path);
        path = path + middlePathName;//"LogData/";
        isExist(path);
        File file = getFile(path, filename);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
//			FileInputStream fis = new FileInputStream(file);
//			long size = fis.available();
//			fis.close();
//			/**
//			 * 当文件大小大于500MByte时，主动删除
//			 */
//			if (autoClear && size >= 500000000)
//			{
//				file.delete();
//				return;
//			}
            FileOutputStream stream = new FileOutputStream(file, true);
            String temp = msg + "\n";
            byte[] buf = temp.getBytes(charsetName);
            stream.write(buf);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 奔溃日志文件
     *
     * @param logFileName
     * @return
     */
    public static String getAPPLogFilePath(String logFileName) {
        String path = getFolderPath();
        isExist(path);
        path = path + "LogData/";
        isExist(path);
        File file = new File(path + logFileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return path + logFileName;
        }
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            long size = fis.available();
            fis.close();
            /**
             * 当文件大小大于50MByte时，主动删除
             */
            if (size >= 50000000) {
                file.delete();
                file.createNewFile();
                return path + logFileName;
            } else {
                return path + logFileName;
            }
        } catch (Exception e) {
            // TODO: handle com.fenda.myutilslibrary.exception
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return path + logFileName;
    }

    public static String uriToPath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            Cursor cursor = null;

            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                // Eat it
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    private static File getFile(String path, String filename) {
        File file = new File(path + filename);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileInputStream fis = new FileInputStream(file);
            long size = fis.available();
            fis.close();
            /**
             * 当文件大小大于500MByte时，主动删除
             */
            if (size >= 500000000) {
                File f = new File(path + System.currentTimeMillis() + filename);
                file.renameTo(f);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LogUtils.e("fileutils","fileName = " +path + filename );
        }
        return new File(path + filename);
    }
    /**
     * 读内存卡中文件方法
     * @param context
     * @param filename 文件名
     * @return
     * @throws IOException
     */
    public static String readInternal(Context context, String filename) throws IOException {
        StringBuilder sb = new StringBuilder("");

        //获取文件在内存卡中files目录下的路径
//        File file = context.getFilesDir();
//        filename = file.getAbsolutePath() + File.separator + filename;

        //打开文件输入流
        FileInputStream inputStream = new FileInputStream(filename);

        byte[] buffer = new byte[1024];
        int len = inputStream.read(buffer);
        //读取文件内容
        while(len > 0){
            sb.append(new String(buffer,0,len));

            //继续将数据放到buffer中
            len = inputStream.read(buffer);
        }
        //关闭输入流
        inputStream.close();
        return sb.toString();
    }
}
